/**
 * Created by zzy on 2017/10/11.
 */

import Store from 'react-native-store';
import {observable, action, computed, observe} from 'mobx' ;
import Contant from "../../js/Contant";
import  {DeviceEventEmitter} from 'react-native';


// DeviceEventEmitter
const DB = {
    user: Store.model('user'),
}

// 登录后的信息存储
class LoginStoreLuo{
    loginState(){
        return new Promise((resolve,reject)=>{
            DB.user.find().then(users=>{
                if(users != null){
                    resolve(true) ;
                }
                else {
                    resolve(false);
                }
            }) ;
        })
    }

    user(){
        return new Promise(function(resolve){
            DB.user.find().then(users=>{
                if(users&&users.length > 0){
                    resolve(users[0])
                }
                else {
                    resolve(null) ;
                }
            })
        });
    }

    // 保存
    save(username,access_token,access_secret){
        DB.user.add(
            {
                username: username,
                access_token: access_token,
                access_token_secret: access_secret,
                login:true
            }).then(()=>{
            DeviceEventEmitter.emit(Contant.LOGINOK);
        });
    }
    //更新
    update(username,access_token,access_secret){
        DB.user.update(
            {
                username: username,
                access_token: access_token,
                access_token_secret: access_secret,
                login:true
            }).then((data)=>{
            DeviceEventEmitter.emit(Contant.LOGINOK);
        });
    }
    wxUpdate(username,access_token,access_secret){
        return new Promise((resolve, reject)=>{
            DB.user.update(
                {
                    username: username,
                    access_token: access_token,
                    access_token_secret: access_secret,
                    login:true
                }).then((data)=>{
                    LOG('微信登录--------'+JSON.stringify(data));
                resolve(data)
            });
        });

    }
    //清除用户信息
    @action
    loginOut(){
        //DB.user.destroy() ;
        DeviceEventEmitter.emit(Contant.LOGINOUT);







    }
}
const loginStore = new LoginStoreLuo() ;
module.exports = loginStore ;